package com.sl.boot.admindemo.commmon.service;

import com.sl.boot.admindemo.commmon.vo.resp.BaseResp;
import com.sl.boot.admindemo.domain.role.user.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class EmailService {
    @Autowired
    private JavaMailSenderImpl mailSender;//一定要用@Autowired

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 给前端输入的邮箱，发送验证码
     */
    public BaseResp sendMimeMail(String email, String code) {

        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();//建立邮件消息
            mailMessage.setFrom(from); //发送者
            mailMessage.setTo(email); //接收者

            mailMessage.setSubject("【医药管理系统】");//主题
            mailMessage.setText("尊敬的用户，您收到的验证码是："+code+"，有效期为5分钟");//内容
            

            mailSender.send(mailMessage);//发送
            return  new BaseResp();
        }catch (Exception e){
            e.printStackTrace();
            log.error("邮件发送失败");
            return new BaseResp(-1, "邮件发送失败");
        }
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
    
}